package com.qfedu.springmvc02.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.springmvc02.entity.User;
import com.qfedu.springmvc02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/userAll")
public class UserAllController {


    @Autowired
    UserService userService;


    //分页查询
    @RequestMapping("page")
    public String page(Integer pageIndex, Model model){
        if (Objects.isNull(pageIndex)){
            pageIndex=1;
        }
        if (pageIndex<1){
            pageIndex=1;
        }
        PageHelper.startPage(pageIndex,5);
        List<User> users = userService.selectAll();
        PageInfo<User> pageInfo = new PageInfo<>(users);
        model.addAttribute("pageInfo",pageInfo);
        return "welcome";
    }


    //添加
    @RequestMapping("add")
    public String add(User user){
        System.out.println(user);
        user.setRegistTime(new Date());
        userService.add(user);

        return "redirect:page";
    }


    //删除
    @RequestMapping("delete")
    public String delete(Integer id){
        userService.delete(id);
        return "redirect:page";
    }

    //修改中转  根据id查信息
    @RequestMapping("selectOne")
    public String selectOne(Integer id,Model model){
        User user = userService.selectOne(id);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
        String birthday = format.format(user.getBirthday());
        String registTime = format.format(user.getRegistTime());
        model.addAttribute("registTime",registTime);
        model.addAttribute("birthday",birthday);
        model.addAttribute("user",user);
        return "update";
    }


    //修改
    @RequestMapping("update")
    public String update(User user){
        userService.update(user);
        return "redirect:page";
    }

    //搜索
    @RequestMapping("search")
    public String search(String name,Model model){

        if (Objects.isNull(name) || name == ""){
            return "redirect:page";
        }
        List<User> users = userService.selectByNameFuzzy(name);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        model.addAttribute("pageInfo",pageInfo);
        return "welcome";
    }
}
